package com.zycfc.zsf.boot.mybatis.generator.codegen.main;

import org.xml.sax.*;
import javax.xml.transform.stream.*;
import javax.xml.validation.*;
import javax.xml.transform.*;
import com.zycfc.zsf.boot.mybatis.generator.codegen.model.*;
import com.zycfc.zsf.boot.mybatis.generator.codegen.exception.*;
import org.dom4j.io.*;
import java.io.*;
import com.zycfc.zsf.boot.mybatis.generator.codegen.util.*;
import org.dom4j.*;
import java.util.*;

public class CodeDelete
{
    private static String xmlPath;
    
    public static void setXmlPath(final String path) {
        CodeDelete.xmlPath = path;
    }
    
    public String validXmlBySchema(final String xsdPath) {
        final SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        final File schemaFile = new File(xsdPath);
        Schema schema = null;
        try {
            schema = schemaFactory.newSchema(schemaFile);
        }
        catch (SAXException e) {
            e.printStackTrace();
        }
        final Validator validator = schema.newValidator();
        final Source source = new StreamSource(FileHelper.getInputStream(CodeDelete.xmlPath));
        try {
            validator.validate(source);
        }
        catch (Exception ex) {
            return ex.getMessage();
        }
        return null;
    }
    
    public ConfigModel loadXml(final String xmlPath) throws Exception {
        final String xsdPath = new File("").getAbsolutePath() + "\\codegen.xsd";
        final String result = this.validXmlBySchema(xsdPath);
        if (result != null) {
            throw new CodegenException("XML\u6587\u4ef6\u901a\u8fc7XSD\u6587\u4ef6\u6821\u9a8c\u5931\u8d25:" + result);
        }
        final ConfigModel cm = new ConfigModel();
        final SAXReader saxReader = new SAXReader();
        Document document = null;
        try {
            document = saxReader.read(new File(xmlPath));
        }
        catch (DocumentException e) {
            throw new CodegenException("\u8bfbXML\u51fa\u9519!", (Throwable)e);
        }
        final Element root = document.getRootElement();
        final Properties prop = new Properties();
        final String pathBase = new File("").getAbsolutePath();
        final InputStream in = new BufferedInputStream(new FileInputStream(pathBase + "\\codegen.properties"));
        prop.load(in);
        final String charset = prop.getProperty("charset");
        final String system = prop.getProperty("system");
        cm.setCharset(charset);
        final Iterator i = root.elementIterator("table");
        while (i.hasNext()) {
            final Element tableEl = i.next();
            final String tableName = tableEl.attributeValue("tableName");
            final ConfigModel.Table table = cm.new Table(tableName);
            final Iterator j = tableEl.elementIterator("variable");
            while (j.hasNext()) {
                final Element fileEl = j.next();
                final String name = fileEl.attributeValue("name");
                final String value = fileEl.attributeValue("value");
                table.getVariable().put(name, value);
            }
            table.getVariable().put("tabname", tableName);
            final Iterator m = tableEl.elementIterator("subtable");
            while (m.hasNext()) {
                final Element subEl = m.next();
                final String tablename = subEl.attributeValue("tablename");
                final String foreignKey = subEl.attributeValue("foreignKey");
                final Map<String, String> vars = new HashMap<String, String>();
                final Iterator var = subEl.elementIterator("variable");
                while (var.hasNext()) {
                    final Element varEl = var.next();
                    final String name2 = varEl.attributeValue("name");
                    final String value2 = varEl.attributeValue("value");
                    vars.put(name2, value2);
                }
                vars.put("tabname", tablename);
                table.addSubTable(tablename, foreignKey, vars);
            }
            cm.getTables().add(table);
        }
        final Element filesEl = root.element("files");
        final ConfigModel.Files files = cm.new Files();
        cm.setFiles(files);
        final String baseDir = filesEl.attributeValue("baseDir");
        files.setBaseDir(baseDir);
        final Iterator k = filesEl.elementIterator("file");
        while (k.hasNext()) {
            final Element fileEl2 = k.next();
            final String refTemplate = fileEl2.attributeValue("refTemplate");
            final String filename = fileEl2.attributeValue("filename");
            final String dir = StringUtil.replaceVariable(fileEl2.attributeValue("dir"), system);
            final String sub = fileEl2.attributeValue("sub");
            final String override = fileEl2.attributeValue("override");
            boolean isOverride = false;
            if (StringUtil.isNotEmpty(override) && override.equals("true")) {
                isOverride = true;
            }
            final String append = fileEl2.attributeValue("append");
            if (append != null && append.toLowerCase().equals("true")) {
                String insertTag = fileEl2.attributeValue("insertTag");
                String startTag = fileEl2.attributeValue("startTag");
                String endTag = fileEl2.attributeValue("endTag");
                if (insertTag == null) {
                    insertTag = "<!--insertbefore-->";
                }
                if (StringUtil.isEmpty(startTag)) {
                    startTag = "";
                }
                if (StringUtil.isEmpty(endTag)) {
                    endTag = "";
                }
                if (sub != null && sub.toLowerCase().equals("true")) {
                    files.addFile(null, filename, dir, true, isOverride, true, insertTag, startTag, endTag);
                }
                else {
                    files.addFile(null, filename, dir, false, isOverride, true, insertTag, startTag, endTag);
                }
            }
            else if (sub != null && sub.toLowerCase().equals("true")) {
                files.addFile(null, filename, dir, true, isOverride, false, "", "", "");
            }
            else {
                files.addFile(null, filename, dir, false, isOverride, false, "", "", "");
            }
        }
        return cm;
    }
    
    public void deleteFileByConfig(final ConfigModel configModel) throws Exception {
        final List<ConfigModel.Table> tableList = configModel.getTables();
        final ConfigModel.Files files = configModel.getFiles();
        final String baseDir = files.getBaseDir();
        final String charset = configModel.getCharset();
        for (final ConfigModel.Table table : tableList) {
            final Map<String, String> variables = table.getVariable();
            final List<ConfigModel.Files.File> list = files.getFiles();
            for (final ConfigModel.Files.File file : list) {
                String filename = file.getFilename();
                String dir = file.getDir();
                filename = StringUtil.replaceVariable(filename, variables);
                dir = StringUtil.replaceVariable(dir, variables);
                final String fileDir = baseDir + "\\" + dir;
                final String startTag = StringUtil.replaceVariable(file.getStartTag(), variables);
                final String endTag = StringUtil.replaceVariable(file.getEndTag(), variables);
                final boolean isAppend = file.getAppend();
                if (isAppend) {
                    this.deleteAppendFile(fileDir, filename, charset, startTag, endTag);
                }
                else {
                    this.deleteFile(fileDir, filename);
                }
            }
            final List<ConfigModel.Table.SubTable> subtables = table.getSubtable();
            if (subtables != null && subtables.size() != 0) {
                for (final ConfigModel.Table.SubTable subtable : subtables) {
                    final Map<String, String> vars = subtable.getVars();
                    for (final ConfigModel.Files.File file2 : list) {
                        String filename2 = file2.getFilename();
                        String dir2 = file2.getDir();
                        if (filename2.indexOf("{") != -1) {
                            final String var = filename2.substring(filename2.indexOf(123) + 1, filename2.indexOf(125));
                            filename2 = vars.get(var) + filename2.substring(filename2.indexOf(125) + 1);
                        }
                        if (dir2.indexOf("{") != -1) {
                            final String var = dir2.substring(dir2.indexOf(123) + 1, dir2.indexOf(125));
                            dir2 = dir2.substring(0, dir2.indexOf(123)) + vars.get(var);
                        }
                        final String fileDir2 = baseDir + "\\" + dir2;
                        final boolean isSub = file2.isSub();
                        final boolean isAppend2 = file2.getAppend();
                        final String startTag2 = StringUtil.replaceVariable(file2.getStartTag(), vars);
                        final String endTag2 = StringUtil.replaceVariable(file2.getStartTag(), vars);
                        if (isSub) {
                            if (isAppend2) {
                                this.deleteAppendFile(fileDir2, filename2, charset, file2.getStartTag(), file2.getEndTag());
                            }
                            else {
                                this.deleteFile(fileDir2, filename2);
                            }
                        }
                    }
                }
            }
        }
    }
    
    private void deleteFile(final String fileDir, final String filename) {
        final String filepath = StringUtil.combilePath(fileDir, filename);
        File file = new File(filepath);
        if (file.exists()) {
            file.delete();
            System.out.println("\u5220\u9664\u4e86\u6587\u4ef6" + filename);
        }
        else {
            System.out.println(filename + "\u8be5\u6587\u4ef6\u4e0d\u5b58\u5728");
        }
        if (!FileHelper.isExistFile(fileDir)) {
            file = new File(fileDir);
            file.delete();
        }
    }
    
    private void deleteAppendFile(final String fileDir, final String filename, final String charset, final String startTag, final String endTag) throws Exception {
        final String filepath = StringUtil.combilePath(fileDir, filename);
        File file = new File(filepath);
        if (file.exists()) {
            final boolean exists = false;
            String content = FileHelper.readFile(filepath, charset);
            if (content.indexOf(startTag) != -1) {
                content = content.substring(0, content.indexOf(startTag)).trim() + "\r\n" + content.substring(content.indexOf(endTag) + endTag.length()).trim();
                file.delete();
                file = new File(filepath);
                FileHelper.writeFile(file, charset, content.trim());
                System.out.println("\u5220\u9664\u4e86\u5185\u5bb9" + startTag + "-----" + endTag);
            }
        }
    }
    
    public void execute() throws Exception {
        final String dir = new File("").getAbsolutePath();
        if (CodeDelete.xmlPath == null || CodeDelete.xmlPath == "") {
            setXmlPath(dir + "\\codegenconfig.xml");
        }
        System.out.println("execute:" + CodeDelete.xmlPath);
        if (CodeDelete.xmlPath == null) {
            throw new CodegenException("\u672a\u6307\u5b9aXML\u8def\u5f84!");
        }
        final ConfigModel cm = this.loadXml(CodeDelete.xmlPath);
        this.deleteFileByConfig(cm);
    }
}
